package com.yuanfeng.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.base.MemberMessageListIntegralDTO;
import com.yuanfeng.commoms.dto.order.RefundParamDTO;
import com.yuanfeng.commoms.dto.order.WapGoodsSaleSumDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.TimeStampUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.vo.goods.GoodsDetailsListVO;
import com.yuanfeng.commoms.vo.goods.WapGoodsSaleSumUpdateVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.dto.*;
import com.yuanfeng.order.entity.*;
import com.yuanfeng.order.feign.BusinessServiceClient;
import com.yuanfeng.order.feign.GoodServiceClient;
import com.yuanfeng.order.feign.PayMentServiceClient;
import com.yuanfeng.order.mapper.OrderBaseMapper;
import com.yuanfeng.order.mapper.OrderGoodsMapper;
import com.yuanfeng.order.mapper.OrderReturnMapper;
import com.yuanfeng.order.mapper.OrderReturnPlatformMapper;
import com.yuanfeng.order.service.OrderCommissionService;
import com.yuanfeng.order.service.OrderReturnPlatformService;
import com.yuanfeng.order.service.OrderSupplierBaseService;
import com.yuanfeng.order.vo.OrderReturnPlatformVO;
import com.yuanfeng.order.vo.ReturnOrderDetailVO;
import com.yuanfeng.order.vo.ReturnOrderDetailsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class OrderReturnPlatformServiceImpl extends ServiceImpl<OrderReturnPlatformMapper, OrderReturnPlatformEntity>
    implements OrderReturnPlatformService{

    @Resource
    private OrderReturnMapper orderReturnMapper;

    @Resource
    private OrderBaseMapper orderBaseMapper;

    @Resource
    private OrderGoodsMapper orderGoodsMapper;
    @Resource

    @Autowired
    private BusinessServiceClient businessServiceClient;

    @Autowired
    private PayMentServiceClient payMentServiceClient;

    @Autowired
    private GoodServiceClient goodServiceClient;

    @Autowired
    private OrderReturnServiceImpl orderReturnServiceImpl;

    @Autowired
    private OrderBaseServiceImpl orderBaseService;

    @Autowired
    private OrderSupplierBaseService orderSupplierBaseService;

    @Autowired
    private OrderCommissionService orderCommissionService;

    @Override
    public ResponseResult insertPlatformIntervention(Map<String, Object> map) {
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(map.get("token").toString());
        if (null == ui) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
        }
        Integer integer = 0;
        String orderId = String.valueOf(map.get("orderId"));
        //查询退款详情
        ReturnOrderDetailVO returnOrderDetail = orderReturnMapper.queryOrderReturnDetail(orderId);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Date Application_time = calendar.getTime();
        calendar.add(Calendar.DATE, 1);
        Date calendarTime = calendar.getTime();
        //平台介入
        if (returnOrderDetail != null) {
            OrderReturnPlatformVO orderReturnPlatform = new OrderReturnPlatformVO();
            OrderReturnPlatformVO orderReturn = this.baseMapper.selectOrderReturnPlatform(orderId);
            if (orderReturn != null) {
                List<String> complaintsImages = (List<String>) map.get("buyerVoucher");
                String buyer_voucher = JSON.toJSONString(complaintsImages);
                orderReturnPlatform.setBuyerVoucher(buyer_voucher);
                orderReturnPlatform.setOrderId(orderId);
                orderReturnPlatform.setBuyerRemarks(String.valueOf(map.get("buyerRemarks")));
                if (orderReturn.getReturnState() == 3 || orderReturn.getReturnState() == 10) {
                    orderReturnPlatform.setReturnState(Integer.parseInt(returnOrderDetail.getReturnState()));
                } else {
                    orderReturnPlatform.setReturnState(null);
                }
                orderReturnPlatform.setReturnMethodType(returnOrderDetail.getReturnMethodStatus());
                if (orderReturn.getInterventionState() == 3 || orderReturn.getInterventionState() == 2) {
                    orderReturnPlatform.setExpriationTime(calendarTime);
                    orderReturnPlatform.setApplicationTime(Application_time);
                    Integer integer1 = orderReturnMapper.updateOrderReturnState(orderId, calendarTime);
                }
                orderReturnPlatform.setInterventionState(0);
                integer = this.baseMapper.updateOrderReturnBuyerVoucher(orderReturnPlatform);
            } else {
                List<String> complaintsImages = (List<String>) map.get("buyerVoucher");
                String buyer_voucher = JSON.toJSONString(complaintsImages);
                orderReturnPlatform.setOrderId(returnOrderDetail.getOrderId());
                orderReturnPlatform.setReturnCode(returnOrderDetail.getReturnCode());
                orderReturnPlatform.setShopName(returnOrderDetail.getShopName());
                orderReturnPlatform.setShopId(returnOrderDetail.getShopId());
                orderReturnPlatform.setSellerUserId(returnOrderDetail.getShopId());
                orderReturnPlatform.setBuyerUserId(returnOrderDetail.getBuyerUserId());
                orderReturnPlatform.setReturnState(Integer.parseInt(returnOrderDetail.getReturnState()));
                orderReturnPlatform.setInterventionState(0);
                orderReturnPlatform.setApplicationTime(Application_time);
                orderReturnPlatform.setExpriationTime(calendarTime);
                orderReturnPlatform.setBuyerVoucher(buyer_voucher);
                orderReturnPlatform.setBuyerRemarks(String.valueOf(map.get("buyerRemarks")));
                orderReturnPlatform.setReturnMethodType(returnOrderDetail.getReturnMethodStatus());
                integer = this.baseMapper.insertOrderReturnPlatform(orderReturnPlatform);

                Integer integer1 = orderReturnMapper.updateOrderReturnState(orderId, calendarTime);
            }
        }
        if (integer > 0) {
            orderBaseMapper.updateOrderBaseReturnMethodStatus(returnOrderDetail.getReturnMethodStatus(), orderId);

            //更改售后单状态为平台介入
            Integer integer1 = orderReturnMapper.update(null,new LambdaUpdateWrapper<OrderReturnEntity>()
                                .set(OrderReturnEntity::getReturnState, CommonType.returnState.PLATFORM_INTERVENTION.getCode())
                                .eq(OrderReturnEntity::getOrderId,orderId));
            if (integer1 > 0) {
                return ResponseResult.success();
            }
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult checkplatform(Map<String, Object> map) {
        String orderId = String.valueOf(map.get("orderId"));
        //查询平台介入
        Integer orderReturnPlatform = this.baseMapper.selectCount(new LambdaQueryWrapper<OrderReturnPlatformEntity>()
                                        .eq(OrderReturnPlatformEntity::getOrderId,orderId));
        if (orderReturnPlatform > 0){

            return ResponseResult.success(1,"有平台介入信息",1);
        }else{
            return ResponseResult.success(1,"无平台介入信息",2);
        }
    }

    @Override
    public ResponseResult queryPlatformIntervention(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO userInfoVO = ParseTokenUtils.getPlatformUser(token);
        if (userInfoVO == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

        String orderId = String.valueOf(map.get("orderId"));
        //查询平台介入
        OrderReturnPlatformVO orderReturnPlatform = this.baseMapper.selectOrderReturnPlatform(orderId);
        if (orderReturnPlatform != null) {
            //计算店铺评分
            Map<Object, Object> map1 = new HashMap();
            map1.put("shopId", orderReturnPlatform.getShopId());
            ResponseResult shopScore = businessServiceClient.shopScore(map1);
            Map data = (Map) shopScore.getData();
            Double evaluationDeliverycredit = (Double) data.get("evaluationDeliverycredit");
            Double evaluation_desccredit = (Double) data.get("evaluationDesccredit");
            Double evaluation_servicecredit = (Double) data.get("evaluationServicecredit");
            Double shopRating = (evaluation_servicecredit + evaluation_desccredit + evaluationDeliverycredit) / 3;
            BigDecimal tmp = new BigDecimal(shopRating);
            shopRating = tmp.setScale(1, RoundingMode.HALF_UP).doubleValue();
            orderReturnPlatform.setShopRating(String.valueOf(shopRating));

            String buyer_voucher = orderReturnPlatform.getBuyerVoucher();
            String seller_voucher = orderReturnPlatform.getSellerVoucher();
            if (seller_voucher != null) {
                List<String> imgs = JSONArray.parseArray(seller_voucher, String.class);
                orderReturnPlatform.setSellerVouchers(imgs);
                orderReturnPlatform.setSellerVoucher(null);
            }
            if (buyer_voucher != null) {
                List<String> imgs = JSONArray.parseArray(buyer_voucher, String.class);
                orderReturnPlatform.setBuyerVouchers(imgs);
                orderReturnPlatform.setBuyerVoucher(null);
            }
        }

        //查询退款详情
        ReturnOrderDetailVO returnOrderDetail = this.baseMapper.queryOrderReturnDetail(orderId);
        //查询售后商品
        List<GoodsDetailsListVO> orderGoods = this.baseMapper.queryGoodsList1(orderId);
        //查询历史维权条数
        Integer integer = this.baseMapper.queryShopIdByCount(returnOrderDetail.getShopId());
        orderReturnPlatform.setHistoricalCount(integer);
        if (orderGoods != null && !orderGoods.isEmpty()) {
            returnOrderDetail.setOrderGoodsDetail(orderGoods);
            orderReturnPlatform.setReturnOrderDetail(returnOrderDetail);
            return ResponseResult.success(orderReturnPlatform);
        }
        return ResponseResult.fail(2, "失败");
    }

    @Override
    public ResponseResult forPlatformApprove(Map<String, String> map) {
        String token = map.get("token");
        UserInfoVO userInfoVO = ParseTokenUtils.getPlatformUser(token);
        if (userInfoVO == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        Boolean torf = forPlatformApproveBoolean(map);
        if (!torf) {
            return ResponseResult.fail(2,"申请退款失败");
        }
        return ResponseResult.success(1,"申请退款成功");

    }

    @Override
    public ResponseResult returnforPlatformApprove(Map<String, String> map) {
        String token = map.get("token");
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(token);
        if (userInfo == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

        map.put("orderOperator", userInfo.getUserAccount());
        map.put("userId", userInfo.getUserId());
        map.put("shopId", userInfo.getShopId());
        Boolean torf = forPlatformApproveBoolean(map);
        if (!torf) {
            return ResponseResult.fail(2,"申核失败");
        }
        return ResponseResult.success(1,"申核成功");
    }

    @Override
    public ResponseResult queryReturnPlatform(OrderReturnPlatformListDTO map) {
        try {
            Page<OrderReturnPlatformListDTO> page = new Page<>(map.getPage(),map.getLimit());
            IPage<OrderReturnPlatformListDTO> selectreturnplatform = this.baseMapper.selectreturnplatform(page,map);
            return ResponseResult.success(PageUtils.getPage(selectreturnplatform));
        } catch (Exception e) {
            return ResponseResult.fail(2,e.getMessage());
        }
    }

    @Override
    public ResponseResult checkPlatformInfo(Map<String, Object> map) {
        String orderId = String.valueOf(map.get("orderId"));
        //查询平台介入
        Integer orderReturnPlatform = this.baseMapper.selectOrderReturnPlatform1(orderId);
        if (orderReturnPlatform > 0){
            return ResponseResult.success(1,"有平台介入信息",1);
        }
        return ResponseResult.fail(2,"无平台介入信息",2);
    }

    @Transactional
    public Boolean forPlatformApproveBoolean(Map<String, String> paraMap) {
        Map<String, Object> orderGoodsMap = new HashMap<String, Object>();
        Map<String, Object> orderBaseMap = new HashMap<String, Object>();
        Map<String,Object> assetDetailMap = new HashMap<>();
        OrderReturnPlatformVO platform = new OrderReturnPlatformVO();
//        String orderId = orderReturnMapper.getOrderIdByReturnCode(paraMap.get("returnCode"));
        OrderReturnEntity returnEntity = orderReturnMapper.selectOne(new LambdaQueryWrapper<OrderReturnEntity>()
                .eq(OrderReturnEntity::getReturnCode,paraMap.get("returnCode")));
        String orderId = returnEntity.getOrderId();
        OrderBaseEntity entity = orderBaseMapper.selectById(orderId);
        paraMap.put("userId",returnEntity.getSellerUserId());
        paraMap.put("shopId",returnEntity.getShopId().toString());
        Integer orderStatus = orderReturnMapper.queryOrderStatus(orderId);
        Integer virtualGoods = 1;
        //获取退货数量
        Map<String,Object> goodsNumMap = new HashMap<>();
        List<Map<String,Object>> goodsNum = orderReturnMapper.queryBuyNumByorderId(orderId);
        goodsNumMap.put("goodsNum",goodsNum);
        String buyerUserId = goodsNum.get(0).get("buyer_user_id").toString();
        //判断是否是虚拟订单 且没有被核销
        Map<String, Object> map  = orderReturnMapper.selectisVirtualOrderByTime(orderId);
        if(null  != map){
            virtualGoods = 0;
            //如果该虚拟订单已过期 且过期不退款直接返回false
            Integer result = orderReturnMapper.queryisVirtualOrderByTime(orderId);
            if( 0 != result){
                return false;
            }
        }
        int type = Integer.parseInt(paraMap.get("type"));
        // 平台同意
        if (1 == Integer.parseInt(paraMap.get("type"))) {
            //查询用户售后商品
            List<Integer> returnGoods = this.baseMapper.queryReturnGoods(orderId);
            BigDecimal returnCash;
            //用户收到货物退款
            if(orderStatus == 6){
                orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
                orderGoodsMap.put("returnShopHandle", 2);
                //4-卖家收到货物
                orderGoodsMap.put("returnState", 2);
                orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
                orderGoodsMap.put("returnFinishTime", TimeStampUtil.getNowDate());

                //	 1.2修改商家同意订单状态为 6
                orderBaseMap.put("orderId",orderId);
                //9.已退款
                orderBaseMap.put("orderStatus","9");
                //2是退款完成
                orderBaseMap.put("orderRefundStatus","2");
                //2是退款完成
                orderBaseMap.put("orderReturnStatus","0");
                Integer torf = orderReturnMapper.updateOrderBaseById(orderBaseMap);

                //修改平台介入表
                platform.setProcessingResults(type);
                platform.setInterventionState(2);
                platform.setProcessingTime(new Date());
                platform.setOrderId(orderId);
                this.baseMapper.examineIntervention(platform);

                Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
                updateGoodsMap.put("orderId",orderId);
                updateGoodsMap.put("goodsRefundStatus",2);
                updateGoodsMap.put("goodsReturnStatus",0);
                updateGoodsMap.put("orderGoodsStatus",9);
                orderReturnMapper.updateOrderGoodsById(updateGoodsMap);

                String uOrderId = orderReturnMapper.queryPaymentNumber(orderId);
                returnCash = orderReturnMapper.queryReturnCash(orderId);

                List<Integer> orderTradeStatus = orderReturnMapper.queryOrderRecordStatus(uOrderId);
                RefundParamDTO refundPara = new RefundParamDTO();
                boolean isRefundSuccess = false;
                if(torf == 1){
                    refundPara = orderReturnMapper.queryRefundPara(orderId);
                    refundPara.setOrderTradeStatus(orderTradeStatus);
                    refundPara.setReturnCash(returnCash);
                    isRefundSuccess = orderReturnServiceImpl.waitShipmentsRefund(refundPara);
                    //退款更新商品销量
                    orderReturnServiceImpl.updateGoodsSalenum(goodsNumMap);
                }
                if(!isRefundSuccess){
                    // 回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                if (1 != torf ) {
                    // 回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                //退还积分
                orderReturnServiceImpl.refundpoints(orderId,returnCash);

                //退还红包优惠卷
                orderReturnServiceImpl.returnred(orderId,returnCash,returnGoods);
                //已发货退款  且是普通商品 不能是虚拟商品
            }else if(orderStatus == 4 && virtualGoods == 1){
                orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
                orderGoodsMap.put("returnShopHandle", 2);
                orderGoodsMap.put("returnState", 2);
                orderGoodsMap.put("returnShopMessage", paraMap.get("returnShopMessage"));
                orderGoodsMap.put("returnShopTime", new Date());

                //	 1.2修改商家同意订单状态为 6
                orderBaseMap.put("orderId",orderId);
                orderBaseMap.put("orderStatus","9");
                orderBaseMap.put("orderRefundStatus","2");
                orderBaseMap.put("orderReturnStatus","0");
                Integer torf = orderReturnMapper.updateOrderBaseById(orderBaseMap);
                Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
                updateGoodsMap.put("orderId",orderId);
                updateGoodsMap.put("goodsRefundStatus",2);
                orderReturnMapper.updateOrderGoodsById(updateGoodsMap);

                String uOrderId = orderReturnMapper.queryPaymentNumber(orderId);
                returnCash = orderReturnMapper.queryReturnCash(orderId);
                List<Integer> orderTradeStatus = orderReturnMapper.queryOrderRecordStatus(uOrderId);
                RefundParamDTO refundPara = new RefundParamDTO();
                boolean isRefundSuccess = false;
                if(torf == 1){
                    refundPara = orderReturnMapper.queryRefundPara(orderId);
                    refundPara.setOrderTradeStatus(orderTradeStatus);
                    refundPara.setReturnCash(returnCash);
                    isRefundSuccess = orderReturnServiceImpl.waitShipmentsRefund(refundPara);
                    //退款更新商品销量
                    orderReturnServiceImpl.updateGoodsSalenum(goodsNumMap);
                }
                if(!isRefundSuccess){
                    // 回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }

                if (1 != torf ) {
                    // 回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                //未发货退款  虚拟商品订单可以进来
            }else if(orderStatus == 3 || virtualGoods == 0){
                orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
                //平台同意买家审核通过
                orderGoodsMap.put("returnState", 2);
                orderGoodsMap.put("returnFinishTime", TimeStampUtil.getNowDate());

                //	 1.2修改平台同意订单状态为 9
                orderBaseMap.put("orderId",orderId);
                //已退款
                orderBaseMap.put("orderStatus","9");
                orderBaseMap.put("orderRefundStatus","2");
                orderBaseMap.put("orderReturnStatus","0");
                orderBaseMap.put("orderFinishedTime",TimeStampUtil.getNowDate());
                Integer torf = orderReturnMapper.updateOrderBaseById(orderBaseMap);
                Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
                updateGoodsMap.put("orderId",orderId);
                updateGoodsMap.put("goodsRefundStatus",2);
                updateGoodsMap.put("goodsReturnStatus",0);
                updateGoodsMap.put("orderGoodsStatus",9);
                orderReturnMapper.updateOrderGoodsById(updateGoodsMap);

                //修改平台介入表
                platform.setProcessingResults(type);
                platform.setInterventionState(2);
                platform.setProcessingTime(new Date());
                platform.setOrderId(orderId);
                this.baseMapper.examineIntervention(platform);

                String uOrderId = orderReturnMapper.queryPaymentNumber(orderId);
                returnCash = orderReturnMapper.queryReturnCash(orderId);

                List<Integer> orderTradeStatus = orderReturnMapper.queryOrderRecordStatus(uOrderId);
                RefundParamDTO refundPara = new RefundParamDTO();
                boolean isRefundSuccess = false;
                if(torf == 1){
                    refundPara = orderReturnMapper.queryRefundPara(orderId);
                    refundPara.setOrderTradeStatus(orderTradeStatus);
                    refundPara.setReturnCash(returnCash);
                    orderReturnServiceImpl.updateGoodsSalenum(goodsNumMap);
                    if(refundPara.getPayCode() != 12) {
                        isRefundSuccess = orderReturnServiceImpl.waitShipmentsRefund(refundPara);
                    }else{
                        isRefundSuccess = true;
                    }
                }
                if(!isRefundSuccess){
                    // 回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                if (1 != torf ) {
                    // 回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
                //退款成功后 修改库存
                //获取goodsid commonid 购买数量
                List<WapGoodsSaleSumUpdateVO> wapGood = orderReturnMapper.queryGoodsXinXi(orderId);
                for (WapGoodsSaleSumUpdateVO wapGoodsSaleSumUpdate : wapGood) {
                    orderReturnMapper.updateCommonStockByGoodsId(wapGoodsSaleSumUpdate);
                    orderReturnMapper.updateGoodsStockByGoodsId(wapGoodsSaleSumUpdate);

                    //遍历集合减去销量
                    orderReturnMapper.lessgoodsBySales(wapGoodsSaleSumUpdate);
                }
                //退还红包优惠卷
                orderReturnServiceImpl.returnred(orderId,returnCash,returnGoods);
            }else{
                return false;
            }
            // 售后分销佣金处理
            orderReturnServiceImpl.commissionReturn(orderId,returnCash);

            // 代发货订单 经销商和供应商佣金处理
            BigDecimal totalDealerCommission = BigDecimal.ZERO;
            BigDecimal totalSupplyCommission = BigDecimal.ZERO;
            List<OrderSupplyCommissionDTO> supplyCommissionList = orderReturnMapper.queryOrderSupplyCommission(orderId);
            for(OrderSupplyCommissionDTO orderSupplyCommission : supplyCommissionList) {
                if (null != orderSupplyCommission && !returnCash.equals(new BigDecimal("0.00"))) {
                    // 退还的经销商和分销商佣金
                    BigDecimal returnDealerCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(), 2,
                            BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getDealerCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal returnSupplCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(), 2,
                            BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getSupplyCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    orderSupplyCommission.setDealerReturnCommission(returnDealerCommission);
                    orderSupplyCommission.setSupplyReturnCommission(returnSupplCommission);
                    // 订单总的退还佣金
                    totalDealerCommission = totalDealerCommission.add(returnDealerCommission);
                    totalSupplyCommission = totalSupplyCommission.add(totalSupplyCommission);
                }
            }
            // 由于退款 是全订单退款 所以退红包
            orderReturnMapper.updateHongbaoStart(orderId);
            //更新商品订单退还佣金
            orderReturnMapper.updateOrderGoodsCommissionBatch(supplyCommissionList);
            // 更新订单退还佣金
            orderReturnMapper.updateOrderSupplyCommission(orderId,totalDealerCommission,totalSupplyCommission);

            //扣除分销佣金
            Map<String,Object> mapFx = this.baseMapper.queryFXCommon(orderId);
            //插入我的余额明细表
            assetDetailMap.put("orderId",orderId);
            assetDetailMap.put("detailType",2);
            assetDetailMap.put("assetType",1);
            assetDetailMap.put("assetAmount",returnCash);
            AssetDirectionAndPayTypeInfoDTO assetInfo = orderReturnMapper.getAssetDirectionAndPayTypeInfo(orderId);
            if(null != assetInfo){
                assetDetailMap.put("assetDirection",assetInfo.getAssetDirection());
                assetDetailMap.put("payType",assetInfo.getPayType());
                assetDetailMap.put("userId",assetInfo.getUserId());
                orderReturnMapper.insertDetail(assetDetailMap);
            }//判断是否是虚拟订单 且没有被核销
            if(null  != map){
                virtualGoods = 0;
                //是否核销 0是 1否 2已过期
                Integer isCancel = Integer.parseInt(map.get("isCancel").toString());
                if(null != isCancel && 0 != isCancel) {
                    //如果该虚拟订单已过期 且过期不退款直接返回false
                    Integer result = orderReturnMapper.queryisVirtualOrderByTime(orderId);
                    if (0 != result) {
                        return false;
                    }
                    boolean returnFlag = false;
                    //未核销且在有效期内
                    if( 1 == isCancel){
                        Integer result1 = orderReturnMapper.queryisVirtualOrderByTime1(orderId);
                        if(null != result1 && result1 >0){
                            returnFlag = true;
                        }
                        //过期且可过期退款
                    }else if( 2 == isCancel){
                        Integer result2 = orderReturnMapper.queryisVirtualOrderByTime2(orderId);
                        if(null != result2 && result2 >0){
                            returnFlag = true;
                            //退还虚拟订单佣金
                            //如果该虚拟订单已过期 且过期允许退款就扣除积分
                            //扣减积分
                            //修改会员积分和会员等级
                            //根据orderid 查询应该回退的积分和userid
                            Map<String, Object> tmpMap = orderReturnMapper.queryAddpointsLogByOrderId(orderId);
                            if (null != tmpMap) {
                                MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
                                ArrayList<String> list = new ArrayList<>();
                                list.add((String) tmpMap.get("user_id"));
                                updateMemberMessageListIntegral.setUserIdList(list);
                                updateMemberMessageListIntegral.setIntegral((Integer) tmpMap.get("points_log_points"));
                                updateMemberMessageListIntegral.setType(0);//1是增加积分 0 是扣除积分
                                orderReturnServiceImpl.feignUpdateMemberIntegral(updateMemberMessageListIntegral);
                                //添加积分修改记录
                                UserPointLogParamDTO userPointLog = new UserPointLogParamDTO();
                                userPointLog.setPointsLogType(2);
                                userPointLog.setClassId(9);
                                userPointLog.setPointsLogTime(new Date());
                                userPointLog.setPointsLogDesc("商品退款");
                                userPointLog.setPointsLogFlag("reg");
                                userPointLog.setUserId((String) tmpMap.get("user_id"));
                                userPointLog.setPointsLogPoints((Integer) tmpMap.get("points_log_points"));
                                userPointLog.setPointsLogOperate("商品退款");
                                userPointLog.setOrderId(paraMap.get("orderId"));
                                orderReturnMapper.feginAddpointsLog(userPointLog);
                            }

                        }
                    }
                    if(returnFlag){
                        Map<String, Object> dataMap = orderReturnMapper.queryOrderReturnInfoById(orderId);
                        if (entity.getOrderPaymentAmount().compareTo(returnCash) > 0) {
                            BigDecimal lv = returnEntity.getReturnCash().divide(entity.getOrderPaymentAmount(), 2, RoundingMode.HALF_UP);
                            if(entity.getOrderCommissionFee() != null) {
                                dataMap.put("orderCommissionFee", BigDecimal.valueOf(entity.getOrderCommissionFee()).multiply(lv).setScale(2, RoundingMode.HALF_UP));
                            }
                            if(entity.getBaseMemberDiscount() != null) {
                                dataMap.put("baseMemberDiscount", BigDecimal.valueOf(entity.getBaseMemberDiscount()).multiply(lv).setScale(2, RoundingMode.HALF_UP));
                            }
                            if(entity.getDistributionDiscount() != null) {
                                dataMap.put("distributionDiscount", entity.getDistributionDiscount().multiply(lv).setScale(2, RoundingMode.HALF_UP));
                            }}
                        dataMap.put("orderId",orderId);
                        orderReturnMapper.updateOrderReturnInfoById(dataMap);
                    }

                }
            }
            //罚扣质保金
            orderReturnServiceImpl.charging(orderId,returnGoods,paraMap.get("userId"),
                    Integer.valueOf(paraMap.get("shopId")));

            //退回plus折扣额度
            try {
                orderBaseService.plusdis(orderId,buyerUserId,returnGoods);
            } catch (ParseException e) {

            }
        } else {
            // 平台不同意
            orderGoodsMap.put("returnCode", paraMap.get("returnCode"));
            orderGoodsMap.put("returnState", 8);
            orderGoodsMap.put("closeTime", new Date());
            Map<String, Object> updateMap = new HashMap<String, Object>();
            Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
            Integer torfOne = null;
            Integer torfTwo = null;
            updateMap.put("orderId", orderId);
            // 原值：2，现改为0，用户可持续申请
            updateMap.put("orderRefundStatus", "0");
            if(orderStatus == 6) {
                updateMap.put("orderStatus", 6);
            }else if(orderStatus == 3 || virtualGoods == 0){
                updateMap.put("orderStatus", 3);
            }
            updateGoodsMap.put("orderId",orderId);
            updateGoodsMap.put("goodsReturnStatus",0);
            updateGoodsMap.put("goodsRefundStatus",0);
            //添加商家拒绝退款时间
            String businessTime =String.valueOf(System.currentTimeMillis());
            String businessRefundTime=TimeStampUtil.stampToDate(businessTime);
            torfOne = orderReturnMapper.updateOrderBaseById(updateMap);

            //修改平台介入表
            platform.setProcessingResults(type);
            platform.setInterventionState(2);
            platform.setProcessingTime(new Date());
            platform.setOrderId(orderId);
            this.baseMapper.examineIntervention(platform);

            //更新record表状态
            Map<String,String> feignMap = new HashMap<>();
            feignMap.put("orderId",orderId);
            // 原值：7
            feignMap.put("recordStatus","8");
            payMentServiceClient.updateRefuse(feignMap);
            if (1 != torfOne ) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }
        Integer torf = orderReturnMapper.updateOrderReturnById(orderGoodsMap);
        if (1 == torf) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean platformUpdate() {
        List<ReturnOrderDetailVO> returnOrderDetails = orderReturnMapper.updateplatform1();
        Calendar instance = Calendar.getInstance();
        if (!CollectionUtils.isEmpty(returnOrderDetails)){
            for (ReturnOrderDetailVO returnOrderDetail : returnOrderDetails) {
                instance.setTime(returnOrderDetail.getExpirationTime());
                instance.add(Calendar.DATE,7);

                orderReturnMapper.updateplatform(returnOrderDetail.getOrderId(),instance.getTime());
            }

        }
        return true;
    }

    @Override
    public Boolean updateTimeOutReturnplatform() {
        //退货
        List<ReturnOrderDetailsVO> orderDetails = this.baseMapper.updateTimeOutReturnplatform();
        shoptimeout(orderDetails);

        //退款
        List<ReturnOrderDetailsVO> detailList =  this.baseMapper.updateTimeOutReturnfundplatform();
        Map<String, Object> orderGoodsMap = new HashMap<String, Object>();
        Map<String, Object> orderBaseMap = new HashMap<String, Object>();
        Map<String,Object> assetDetailMap = new HashMap<>();
        if (detailList != null && detailList.size() > 0 ){
            for (ReturnOrderDetailsVO map1 : detailList) {
                String orderId = map1.getOrderId();
                String returnCode = map1.getReturnCode();
                OrderBaseEntity orderBaseEntity=orderBaseMapper.selectById(orderId);
                Integer orderStatus = orderBaseEntity.getOrderStatus();
                Integer virtualGoods = 1;
                //获取退货数量
                Map<String,Object> goodsNumMap = new HashMap<>();
                List<Map<String,Object>> goodsNum =  orderReturnMapper.queryBuyNumByorderId(orderId);
                goodsNumMap.put("goodsNum",goodsNum);
                //判断是否是虚拟订单 且没有被核销
                Map<String, Object> map = orderReturnMapper.selectisVirtualOrderByTime(orderId);
                if(null  != map){
                    virtualGoods = 0;
                    //如果该虚拟订单已过期 且过期不退款直接返回false
                    Integer result = orderBaseMapper.queryisVirtualOrderByTime(orderId);
                    if( 0 != result){
                        return false;
                    }
                }
                BigDecimal returnCash;
                if(orderStatus == 6){
                    //用户收到货物退款
                    orderGoodsMap.put("returnCode", returnCode);
                    orderGoodsMap.put("returnShopHandle", 2);
                    orderGoodsMap.put("returnState", 2);


                    //	 1.2修改商家同意订单状态为 6
                    orderBaseMap.put("orderId",orderId);
                    //9.已退款
                    orderBaseMap.put("orderStatus","9");
                    //2是退款完成
                    orderBaseMap.put("orderRefundStatus","2");
                    //2是退款完成
                    orderBaseMap.put("orderReturnStatus","0");
                    Integer torf = orderBaseMapper.updateOrderBaseById(orderBaseMap);

                    Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
                    updateGoodsMap.put("orderId",orderId);
                    updateGoodsMap.put("goodsRefundStatus",2);
                    updateGoodsMap.put("goodsReturnStatus",0);
                    orderReturnMapper.updateOrderGoodsById(updateGoodsMap);

                    String uOrderId = orderBaseEntity.getPaymentNumber();
                    returnCash= orderReturnMapper.selectOne(new LambdaQueryWrapper<OrderReturnEntity>()
                            .eq(OrderReturnEntity::getOrderId,orderId)).getReturnCash();

                    List<Integer> orderTradeStatus =orderReturnMapper.queryOrderRecordStatus(orderBaseEntity.getPaymentNumber());
                    RefundParamDTO refundPara = new RefundParamDTO();
                    boolean isRefundSuccess = false;
                    if(torf == 1){
                        refundPara = orderReturnMapper.queryRefundPara(orderId);
                        refundPara.setOrderTradeStatus(orderTradeStatus);
                        refundPara.setReturnCash(returnCash);
                        isRefundSuccess = orderReturnServiceImpl.waitShipmentsRefund(refundPara);
                        //退款更新商品销量
                        orderReturnServiceImpl.updateGoodsSalenum(goodsNumMap);
                    }
                    if(!isRefundSuccess){
                        // 回滚
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return false;
                    }
                }else if(orderStatus == 3 || virtualGoods == 0){
                    //未发货退款  虚拟商品订单可以进来
                    orderGoodsMap.put("returnCode", returnCode);
                    orderGoodsMap.put("returnShopHandle", 2);
                    //卖家审核通过
                    orderGoodsMap.put("returnState", 2);
                    orderGoodsMap.put("returnFinishTime", DateUtils.getNowDate());

                    //	 1.2修改商家同意订单状态为 6
                    orderBaseMap.put("orderId",orderId);
                    //已退款
                    orderBaseMap.put("orderStatus", CommonType.orderStatus.REFUNDED.getCode());
                    orderBaseMap.put("orderRefundStatus","2");
                    orderBaseMap.put("orderReturnStatus","0");
                    orderBaseMap.put("orderFinishedTime",DateUtils.getNowDate());
                    Integer torf = orderBaseMapper.updateOrderBaseById(orderBaseMap);
                    Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
                    updateGoodsMap.put("orderId",orderId);
                    updateGoodsMap.put("goodsRefundStatus",2);
                    updateGoodsMap.put("goodsReturnStatus",0);
                    orderReturnMapper.updateOrderGoodsById(updateGoodsMap);

                    String uOrderId = orderBaseEntity.getPaymentNumber();
                    returnCash= orderReturnMapper.selectOne(new LambdaQueryWrapper<OrderReturnEntity>()
                            .eq(OrderReturnEntity::getOrderId,orderId)).getReturnCash();

                    List<Integer> orderTradeStatus =orderReturnMapper.queryOrderRecordStatus(orderBaseEntity.getPaymentNumber());
                    RefundParamDTO refundPara = new RefundParamDTO();
                    boolean isRefundSuccess = false;
                    if(torf == 1){
                        refundPara = orderReturnMapper.queryRefundPara(orderId);
                        refundPara.setOrderTradeStatus(orderTradeStatus);
                        refundPara.setReturnCash(returnCash);
                        orderReturnServiceImpl.updateGoodsSalenum(goodsNumMap);
                        if(refundPara.getPayCode() != 12) {
                            isRefundSuccess = orderReturnServiceImpl.waitShipmentsRefund(refundPara);
                        }else{
                            isRefundSuccess = true;
                        }
                    }
                    if(!isRefundSuccess){
                        // 回滚
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return false;
                    }
                    //退款成功后 修改库存
                    //获取goodsid commonid 购买数量
                    List<WapGoodsSaleSumUpdateVO> wapGood = orderReturnMapper.queryGoodsXinXi(orderId);
                    //封装数据
                    List<WapGoodsSaleSumDTO> wapGoodData = new ArrayList<>();
                    if (!CollectionUtils.isEmpty(wapGood)) {
                        wapGoodData = wapGood.stream().map(entity -> {
                            WapGoodsSaleSumDTO catResult = new WapGoodsSaleSumDTO();

                            BeanUtils.copyProperties(entity, catResult);
                            return catResult;
                        }).collect(Collectors.toList());
                    }
                    goodServiceClient.updateGoodsStock(wapGoodData);

                    for (WapGoodsSaleSumUpdateVO goods : wapGood) {
                        //遍历集合减去销量
                        orderReturnMapper.lessgoodsBySales(goods);
                    }
                    //查询红包和代金卷
                    if (null != orderBaseEntity.getVoucherCode()) {
                        //退还代金卷
                        orderReturnMapper.updateCouponStuate(orderBaseEntity.getVoucherCode());
                    }
                    if (null != orderBaseEntity.getRedpacketCode()) {
                        orderReturnMapper.updateRedPageStuate(orderBaseEntity.getRedpacketCode());
                    }
                }else{
                    return false;
                }
                // 售后分销佣金处理
                orderReturnServiceImpl.commissionReturn(orderId,returnCash);

                // 代发货订单 经销商和供应商佣金处理
                BigDecimal totalDealerCommission = BigDecimal.ZERO;
                BigDecimal totalSupplyCommission = BigDecimal.ZERO;
                List<OrderSupplyCommissionDTO> supplyCommissionList = orderReturnMapper.queryOrderSupplyCommission(orderId);

                for(OrderSupplyCommissionDTO orderSupplyCommission : supplyCommissionList) {
                    if (null != orderSupplyCommission && !returnCash.equals(new BigDecimal("0.00"))) {
                        // 退还的经销商和分销商佣金
                        BigDecimal returnDealerCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(), 2, RoundingMode.HALF_UP).multiply(orderSupplyCommission.getDealerCommission()).setScale(2, RoundingMode.HALF_UP);
                        BigDecimal returnSupplCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(), 2, RoundingMode.HALF_UP).multiply(orderSupplyCommission.getSupplyCommission()).setScale(2, RoundingMode.HALF_UP);
                        orderSupplyCommission.setDealerReturnCommission(returnDealerCommission);
                        orderSupplyCommission.setSupplyReturnCommission(returnSupplCommission);
                        // 订单总的退还佣金
                        totalDealerCommission = totalDealerCommission.add(returnDealerCommission);
                        totalSupplyCommission = totalSupplyCommission.add(totalSupplyCommission);
                    }
                }
//			}
//                // 由于退款 是全订单退款 所以退红包
//                orderReturnMapper.updateHongbaoStart(orderId);
//                //更新商品订单退还佣金
//                orderGoodsMapper.updateOrderGoodsCommissionBatch(supplyCommissionList);
//                // 更新订单退还佣金
//                orderBaseMapper.update(null,new LambdaUpdateWrapper<OrderBaseEntity>()
//                        .eq(OrderBaseEntity::getOrderId,orderId)
//                        .set(OrderBaseEntity::getDealerReturnCommission,totalDealerCommission)
//                        .set(OrderBaseEntity::getSupplyReturnCommission,totalSupplyCommission));

                //扣除分销佣金
//                OrderCommissionEntity mapFx = orderCommissionService.getById(orderId);
//                if(null != mapFx){
//                    Map<String,Object> objectMap=new HashMap<>();
//                    objectMap.put("userId",mapFx.getShareUserId().toString());
//                    objectMap.put("var2",mapFx.getReturnTgCommission());
//                    objectMap.put("var3",mapFx.getReturnFxCommission());
//                    orderCommissionMapper.updateVkCommissionReturn(objectMap);
//                }
                //插入我的余额明细表
                assetDetailMap.put("orderId", orderId);
                assetDetailMap.put("detailType", 2);
                assetDetailMap.put("assetType", 1);
                assetDetailMap.put("assetAmount", returnCash);
                AssetDirectionAndPayTypeInfoDTO assetInfo = orderReturnMapper.getAssetDirectionAndPayTypeInfo(orderId);
                if (null != assetInfo) {
                    assetDetailMap.put("assetDirection", assetInfo.getAssetDirection());
                    assetDetailMap.put("payType", assetInfo.getPayType());
                    assetDetailMap.put("userId", assetInfo.getUserId());
                    orderReturnMapper.insertDetail(assetDetailMap);
                }//判断是否是虚拟订单 且没有被核销
                if(null  != map){
                    virtualGoods = 0;
                    //是否核销 0是 1否 2已过期
                    Integer isCancel = Integer.parseInt(map.get("isCancel").toString());
                    if(null != isCancel && 0 != isCancel) {
                        //如果该虚拟订单已过期 且过期不退款直接返回false
                        Integer result = orderBaseMapper.queryisVirtualOrderByTime(orderId);
                        if (0 != result) {
                            return false;
                        }
                        boolean returnFlag = false;
                        //未核销且在有效期内
                        if( 1 == isCancel){
                            Integer result1 = orderReturnMapper.queryisVirtualOrderByTime1(orderId);
                            if(null != result1 && result1 >0){
                                returnFlag = true;
                            }
                            //过期且可过期退款
                        }else if( 2 == isCancel){
                            Integer result2 = orderReturnMapper.queryisVirtualOrderByTime2(orderId);
                            if(null != result2 && result2 >0){
                                returnFlag = true;
                                //退还虚拟订单佣金
                                //如果该虚拟订单已过期 且过期允许退款就扣除积分
                                //扣减积分
                                //修改会员积分和会员等级
                                //根据orderid 查询应该回退的积分和userid
                                Map<String, Object> tmpMap = orderReturnMapper.queryAddpointsLogByOrderId(orderId);
                                if (null != tmpMap) {
                                    MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
                                    ArrayList<String> list = new ArrayList<>();
                                    list.add(tmpMap.get("user_id").toString());
                                    updateMemberMessageListIntegral.setUserIdList(list);
                                    updateMemberMessageListIntegral.setIntegral((Integer) tmpMap.get("points_log_points"));
                                    //1是增加积分 0 是扣除积分
                                    updateMemberMessageListIntegral.setType(0);
                                    orderReturnServiceImpl.feignUpdateMemberIntegral(updateMemberMessageListIntegral);
                                    //添加积分修改记录
                                    UserPointLogParamDTO userPointLog = new UserPointLogParamDTO();
                                    userPointLog.setPointsLogType(2);
                                    userPointLog.setClassId(9);
                                    userPointLog.setPointsLogTime(new Date());
                                    userPointLog.setPointsLogDesc("商品退款");
                                    userPointLog.setPointsLogFlag("reg");
                                    userPointLog.setUserId(tmpMap.get("user_id").toString());
                                    userPointLog.setPointsLogPoints((Integer) tmpMap.get("points_log_points"));
                                    userPointLog.setPointsLogOperate("商品退款");
                                    userPointLog.setOrderId(orderId);
                                    orderReturnMapper.feginAddpointsLog(userPointLog);
                                }

                            }
                        }
                        if(returnFlag){
                            Map<String, Object> dataMap = orderReturnMapper.queryOrderReturnInfoById(orderId);
                            if (orderBaseEntity.getOrderPaymentAmount().compareTo(returnCash) > 0) {
                                BigDecimal lv = returnCash.divide(orderBaseEntity.getOrderPaymentAmount(), 2, RoundingMode.HALF_UP);
                                if(orderBaseEntity.getOrderCommissionFee() != null) {
                                    dataMap.put("orderCommissionFee", BigDecimal.valueOf(orderBaseEntity.getOrderCommissionFee()).multiply(lv).setScale(2, RoundingMode.HALF_UP));
                                }
                                if(orderBaseEntity.getBaseMemberDiscount() != null) {
                                    dataMap.put("baseMemberDiscount", BigDecimal.valueOf(orderBaseEntity.getBaseMemberDiscount()).multiply(lv).setScale(2, RoundingMode.HALF_UP));
                                }
                                if(orderBaseEntity.getDistributionDiscount() != null) {
                                    dataMap.put("distributionDiscount", orderBaseEntity.getDistributionDiscount().multiply(lv).setScale(2, RoundingMode.HALF_UP));
                                }}
                            dataMap.put("orderId",orderId);
                            orderReturnMapper.updateOrderReturnInfoById(dataMap);
                        }
                    }
                }
                Integer torf = orderReturnMapper.updateOrderReturnById(orderGoodsMap);
            }
        }
        return true;
    }


    public Boolean shoptimeout(List<ReturnOrderDetailsVO> orderDetails){
        if (orderDetails != null && orderDetails.size() > 0){
            Map<String, Object> orderGoodsMap = new HashMap<String, Object>();
            Map<String, Object> orderBaseMap = new HashMap<String, Object>();
            for (ReturnOrderDetailsVO orderDetail : orderDetails) {
                String returnCode = orderDetail.getReturnCode();
                if (orderDetail.getReturnState() == 3){
                    orderGoodsMap.put("returnCode", returnCode);
                    //平台5
                    orderGoodsMap.put("returnShopHandle", 2);
                    orderGoodsMap.put("returnState", 2);

                    orderGoodsMap.put("returnAddr", orderDetail.getOrderSellerAddress());
                    orderGoodsMap.put("returnRealName", orderDetail.getOrderSellerName());
                    orderGoodsMap.put("returnNumber", orderDetail.getOrderSellerContact());

                    Calendar instance = Calendar.getInstance();
                    instance.setTime(new Date());
                    instance.add(Calendar.DATE,7);
                    Date expiration_time = instance.getTime();

                    orderGoodsMap.put("expirationTime", expiration_time);
                    Integer torf = orderReturnMapper.updateOrderReturnById(orderGoodsMap);
                    orderGoodsMap.clear();
                }else if(orderDetail.getReturnState() == 10){
                    orderGoodsMap.put("returnCode", returnCode);
                    orderGoodsMap.put("returnShopHandle", 4);
                    orderGoodsMap.put("returnState", 4);
                    orderGoodsMap.put("returnShopTime", new Date());

                    //	 商家确认收货该状态为9已退款
                    String orderId = orderReturnMapper.getOrderIdByReturnCode(returnCode);
                    OrderBaseEntity orderBaseEntity=orderBaseMapper.selectById(orderId);
                    orderBaseMap.put("orderId",orderId);
                    orderBaseMap.put("orderStatus","9");
                    orderBaseMap.put("orderReturnStatus","2");
                    Integer torf = orderBaseMapper.updateOrderBaseById(orderBaseMap);
                    Map<String, Object> updateGoodsMap = new HashMap<String, Object>();
                    updateGoodsMap.put("orderId",orderId);
                    updateGoodsMap.put("goodsReturnStatus",2);
                    orderGoodsMapper.updateOrderGoodsById2(updateGoodsMap);
                    String uOrderId = orderReturnMapper.queryPaymentNumber(orderId);
                    BigDecimal returnCash =orderReturnMapper.queryReturnCash(orderId);

                    List<Integer> orderTradeStatus = orderReturnMapper.queryOrderRecordStatus(uOrderId);
                    RefundParamDTO refundPara = new RefundParamDTO();
                    boolean isRefundSuccess = false;
                    if(torf == 1){
                        refundPara = orderReturnMapper.queryRefundPara(orderId);
                        refundPara.setOrderTradeStatus(orderTradeStatus);
                        refundPara.setReturnCash(returnCash);
                        isRefundSuccess = orderReturnServiceImpl.waitShipmentsRefund(refundPara);

                    }
                    if(!isRefundSuccess){
                        // 回滚
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return false;
                    }

                    if (1 != torf ) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return false;
                    }

                    // 分销佣金订单处理
                    orderReturnServiceImpl.commissionReturn(orderId,returnCash);
                    //判断当前订单是否全部退货
                    Boolean huoBaoreturn = true;
                    //平台退货佣金计算  会员折扣计算
                    List<OrderPingtaiCommissionDTO> orderPingtaiCommissions = orderReturnMapper.queryOrderPingTaiCommission(orderId);
                    BigDecimal countPingTaiCommission = new BigDecimal(0);
                    BigDecimal huiYuanZhekou = new BigDecimal(0);
                    for (OrderPingtaiCommissionDTO orderPingtaiCommission : orderPingtaiCommissions) {
                        //下单数量 等于 退单数量 平台抽佣全退
//                        if(orderPingtaiCommission.getGoodsNum().equals(orderPingtaiCommission.getGoodsReturnNum())){
//                            countPingTaiCommission = countPingTaiCommission.add(orderPingtaiCommission.getOrderGoodsCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
//                        }else{
//                            BigDecimal goodsCount = orderPingtaiCommission.getOrderGoodsCommission().divide(new BigDecimal(orderPingtaiCommission.getGoodsNum()),2, BigDecimal.ROUND_HALF_UP);
//                            goodsCount = goodsCount.multiply(new BigDecimal(orderPingtaiCommission.getGoodsReturnNum())).setScale(2, BigDecimal.ROUND_HALF_UP);
//                            countPingTaiCommission = countPingTaiCommission.add(goodsCount).setScale(2, BigDecimal.ROUND_HALF_UP);
//                        }

                        //计算会员折扣
//                        BigDecimal zhekou = orderPingtaiCommission.getGoodsMemberDiscount().divide(new  BigDecimal(orderPingtaiCommission.getGoodsNum()),2, BigDecimal.ROUND_HALF_UP);
//                        zhekou = zhekou.multiply(new BigDecimal(orderPingtaiCommission.getGoodsReturnNum())).setScale(2, BigDecimal.ROUND_HALF_UP);
//                        huiYuanZhekou = huiYuanZhekou.add(zhekou).setScale(2, BigDecimal.ROUND_HALF_UP);
                        if(!orderPingtaiCommission.getGoodsNum().equals(orderPingtaiCommission.getGoodsReturnNum())){
                            huoBaoreturn = false;
                        }
                        //退还同步商品的 佣金
                        if(null != orderPingtaiCommission.getDropShipping() && 1 == orderPingtaiCommission.getDropShipping()){
                            OrderSupplierBaseEntity orderSupplierOrderBaseEntity = orderSupplierBaseService.getById(orderId);
                            BigDecimal supperPrice = orderSupplierOrderBaseEntity.getSupperCommission();
                            supperPrice = supperPrice.divide(new BigDecimal(orderPingtaiCommission.getGoodsNum()),2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal returnSupperPrice = supperPrice.multiply(new BigDecimal(orderPingtaiCommission.getGoodsReturnNum())).setScale(2, BigDecimal.ROUND_HALF_UP);

                            orderSupplierBaseService.update(null,new LambdaUpdateWrapper<OrderSupplierBaseEntity>()
                                    .eq(OrderSupplierBaseEntity::getOrderId,orderId)
                                    .set(OrderSupplierBaseEntity::getSupperReturnCommission,returnSupperPrice));
                        }
                    }
                    //根据退款金额退多少佣金
                    if (orderBaseEntity.getOrderPaymentAmount().compareTo(returnCash) > 0) {
                        BigDecimal lv = returnCash.divide(orderBaseEntity.getOrderPaymentAmount(), 2, RoundingMode.HALF_UP);
                        countPingTaiCommission = BigDecimal.valueOf(orderBaseEntity.getOrderCommissionFee()).multiply(lv).setScale(2, RoundingMode.HALF_UP);
                        huiYuanZhekou = BigDecimal.valueOf(orderBaseEntity.getBaseMemberDiscount()).multiply(lv).setScale(2, RoundingMode.HALF_UP);
                    } else {
                        countPingTaiCommission = BigDecimal.valueOf(orderBaseEntity.getOrderCommissionFee());
                        huiYuanZhekou = BigDecimal.valueOf(orderBaseEntity.getBaseMemberDiscount());
                    }
                    //根据订单号查询支付单号 因为有可能多个订单公用一个支付单号 如果是多个订单共用用一个支付单号 要判断除当前退单外的其他订单是否是全退
                    String paymentNumber = uOrderId;
                    //如果多个订单公用一个支付单号 根据当前订单号 和 支付单号 查询是否有其他订单没有全退货
                    Integer notOrderNum = orderReturnMapper.queryNotRetuenOrder(orderId, uOrderId);
                    if(0 <= notOrderNum){
                        //说明有其他订单没有完全退货 不退红包 优惠券
                        huoBaoreturn = false;
                    }
                    //退货红包 优惠券
                    if(huoBaoreturn){
                        orderReturnMapper.updateHongbaoStart(orderId);
                        orderReturnMapper.updateYouHuiquanStart(orderId);
                    }
                    orderBaseMapper.update(null,new LambdaUpdateWrapper<OrderBaseEntity>()
                            .eq(OrderBaseEntity::getOrderId,orderId)
                            .set(OrderBaseEntity::getOrderCommissionReturnFee,countPingTaiCommission));
                    //更新退款表 平台退还佣金 退还会员折扣
                    orderReturnMapper.update(null,new LambdaUpdateWrapper<OrderReturnEntity>()
                            .eq(OrderReturnEntity::getOrderId,orderId)
                            .set(OrderReturnEntity::getReturnCommisionFee,countPingTaiCommission)
                            .set(OrderReturnEntity::getReturnMemberDiscount,huiYuanZhekou));
                    // 代发货订单 经销商和供应商佣金处理
                    BigDecimal totalDealerCommission = BigDecimal.ZERO;
                    BigDecimal totalSupplyCommission = BigDecimal.ZERO;
                    List<OrderSupplyCommissionDTO> supplyCommissionList = orderReturnMapper.queryOrderSupplyCommission(orderId);
                    for(OrderSupplyCommissionDTO orderSupplyCommission : supplyCommissionList) {
                        if(null != orderSupplyCommission.getOrderGoodsReturnnum()){
                            // 退还的经销商和分销商佣金
                            BigDecimal returnDealerCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(),2, BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getDealerCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal returnSupplCommission = returnCash.divide(orderSupplyCommission.getOrderGoodsPaymentAmount(),2, BigDecimal.ROUND_HALF_UP).multiply(orderSupplyCommission.getSupplyCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            orderSupplyCommission.setDealerReturnCommission(returnDealerCommission);
                            orderSupplyCommission.setSupplyReturnCommission(returnSupplCommission);
                            // 订单总的退还佣金
                            totalDealerCommission = totalDealerCommission.add(returnDealerCommission);
                            totalSupplyCommission = totalSupplyCommission.add(totalSupplyCommission);
                        }
                    }
                    //扣除分销佣金
                    OrderCommissionEntity mapFx = orderCommissionService.getById(orderId);
                    Map<String,Object> objectMap=new HashMap<>();
                    objectMap.put("userId",mapFx.getShareUserId().toString());
                    objectMap.put("var2",mapFx.getReturnTgCommission());
                    objectMap.put("var3",mapFx.getReturnFxCommission());
                    if(null != mapFx){
                        this.baseMapper.updateVkCommissionReturn(objectMap);
                    }
                    //更新商品订单退还佣金
                    orderReturnMapper.updateOrderGoodsCommissionBatch(supplyCommissionList);
                    // 更新订单退还佣金
                    orderBaseMapper.update(null,new LambdaUpdateWrapper<OrderBaseEntity>()
                            .eq(OrderBaseEntity::getOrderId,orderId)
                            .set(OrderBaseEntity::getDealerReturnCommission,totalDealerCommission)
                            .set(OrderBaseEntity::getSupplyReturnCommission,totalSupplyCommission));
                    Map<String,Object> goodsNumMap = new HashMap<>();
                    List<Map<String,Object>> goodsNum = orderReturnMapper.queryBuyNumByorderId(orderId);
                    goodsNumMap.put("goodsNum",goodsNum);
                    //退款更新商品销量
                    orderReturnServiceImpl.updateGoodsSalenum(goodsNumMap);
                    //根据orderid 查询应该回退的积分和userid
                    //根据orderid 查询应该回退的积分和userid
                    Map<String, Object> map = orderReturnMapper.queryAddpointsLogByOrderId(orderId);

                    //ZZZ 新增积分按比例扣除逻辑
                    //订单实付金额
                    BigDecimal orderPaymentAmount = orderBaseEntity.getOrderPaymentAmount();
                    //订单商品总价（不含运费）
                    BigDecimal orderGoodsAmount = orderBaseEntity.getOrderGoodsAmount();
                    //退货商品总价(不含运费）
                    BigDecimal returnAmount = BigDecimal.ZERO;
                    //退货积分系数
                    BigDecimal coef = BigDecimal.ZERO;
                    List<OrderReturnPointsDTO> orderReturnPointsList = orderReturnMapper.queryOrderReturnInfo(orderId);
                    if (null != orderReturnPointsList && orderReturnPointsList.size() > 0) {
                        for (OrderReturnPointsDTO orp : orderReturnPointsList) {
                            BigDecimal goodsPrice = null != orp ? orp.getGoodsPrice() : BigDecimal.ZERO;
                            Integer goodsReturnNum = null != orp ? orp.getOrderGoodsReturnnum() : 0;
                            returnAmount = returnAmount.add(goodsPrice.multiply(new BigDecimal(goodsReturnNum)));
                        }
                    }
                    //实际退款金额(用于计算退还积分)
                    returnAmount = returnAmount.multiply(orderPaymentAmount).divide(orderGoodsAmount, RoundingMode.HALF_UP);
                    //实际退款积分ZZZ
                    BigDecimal tmp = BigDecimal.ZERO;
                    if (null != map && null != map.get("points_log_points")) {
                        tmp = returnAmount.multiply(new BigDecimal((Integer) map.get("points_log_points"))).divide(orderPaymentAmount, RoundingMode.HALF_UP);
                    }
                    Integer tmpInt = tmp.intValue();
                    map.put("points_log_points", tmpInt);
                    //插入我的余额明细表
                    setAssDetails(orderId,returnCash);



                    //修改会员积分和会员等级
                    MemberMessageListIntegralDTO updateMemberMessageListIntegral = new MemberMessageListIntegralDTO();
                    ArrayList<String> list = new ArrayList<>();
                    list.add(map.get("user_id").toString());
                    updateMemberMessageListIntegral.setUserIdList(list);
                    updateMemberMessageListIntegral.setIntegral((Integer) map.get("points_log_points"));
                    //1是增加积分 0 是扣除积分
                    updateMemberMessageListIntegral.setType(0);
                    orderReturnServiceImpl.feignUpdateMemberIntegral(updateMemberMessageListIntegral);
                    //添加积分修改记录
                    UserPointLogParamDTO userPointLog = new UserPointLogParamDTO();
                    userPointLog.setPointsLogType(2);
                    userPointLog.setClassId(9);
                    userPointLog.setPointsLogTime(new Date());
                    userPointLog.setPointsLogDesc("商品退货");
                    userPointLog.setPointsLogFlag("reg");
                    userPointLog.setUserId(map.get("user_id").toString());
                    userPointLog.setPointsLogPoints((Integer) map.get("points_log_points"));
                    userPointLog.setPointsLogOperate("商品退货");
                    userPointLog.setOrderId(orderId);
                    orderReturnMapper.feginAddpointsLog(userPointLog);

                    orderGoodsMap.put("returnFinishTime",new Date());
                    orderReturnMapper.updateOrderReturnById(orderGoodsMap);
                    orderGoodsMap.clear();
                    orderBaseMap.clear();
                }

            }
        }
        return true;
    }


    /**
     * 设置记录
     *
     * @param orderId
     * @param returnCash
     */
    public void setAssDetails(String orderId, BigDecimal returnCash) {
        Map<String, Object> assetDetailMap = new HashMap<>();
        //插入我的余额明细表
        assetDetailMap.put("orderId", orderId);
        assetDetailMap.put("detailType", 2);
        assetDetailMap.put("assetType", 1);
        assetDetailMap.put("assetAmount", returnCash);
        AssetDirectionAndPayTypeInfoDTO assetInfo = orderReturnMapper.getAssetDirectionAndPayTypeInfo(orderId);

//        }
        assetDetailMap.put("assetAmount", returnCash);
        if (null != assetInfo) {
            assetDetailMap.put("assetDirection", assetInfo.getAssetDirection());
            assetDetailMap.put("payType", assetInfo.getPayType());
            assetDetailMap.put("userId", assetInfo.getUserId());
            orderReturnMapper.insertDetail(assetDetailMap);
        }
    }
}




